﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PmSoft;
using PmSoft.Events;

namespace Modules.BankSpecialAccount.EventModules;

[UseDI(ServiceLifetime.Singleton, typeof(IEventMoudle))]
public class BankSpecialAccountModule : IEventMoudle
{
    private readonly IEventBus eventBus;

    public BankSpecialAccountModule(IEventBus eventBus)
    {
        this.eventBus = eventBus;
    }

    public void RegisterEventHandler()
    {
        eventBus.Subscribe<ReviseBalanceEventArgs, ReviseBalanceEventHandler>();
    }
}

#region 处理更新专户余额结果

[UseDI(ServiceLifetime.Scoped)]
public class ReviseBalanceEventHandler : IEventHandler<ReviseBalanceEventArgs>
{
    private readonly BankSpecialAccountService projectSpecialAccountService;
    private readonly ILogger logger;

    public ReviseBalanceEventHandler(BankSpecialAccountService projectSpecialAccountService, ILogger<ReviseBalanceEventHandler> logger)
    {
        this.projectSpecialAccountService = projectSpecialAccountService;
        this.logger = logger;
    }

    /// <summary>
    /// 处理更新专户余额结果
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="eventArgs"></param>
    /// <returns></returns>
    public Task HandleAsync(object sender, ReviseBalanceEventArgs eventArgs)
    {
        var account = projectSpecialAccountService.GetProjectSpecialAccountByCode(eventArgs.Code);
        if (account == null)
        {
            logger.LogWarning($"更新专户余额失败，原因:[Code为{eventArgs.Code}]的专户不存在");
            return Task.CompletedTask;
        }
        if (account != null)
        {
            account.Balance = eventArgs.Balance;
            projectSpecialAccountService.UpdateProjectSpecialAccount(account);
        }

        return Task.CompletedTask;
    }
}

#endregion 处理更新专户余额结果